* ======================================
* ---------- Import distance -----------
* ======================================


* Import files provided by Institute of Transport Economics
* =========================================================

	forvalues i=1(1)15{
		use "$dta_ext\grk_grk_`i'_of_15.dta" , clear
		keep grk1 grk2 dist_km time_min
		rename grk1 bsu_i
		rename grk2 bsu_j
		tostring bsu_i, replace
		tostring bsu_j, replace
		replace bsu_i = "0" + substr(bsu_i,1,7) if strlen(bsu_i) == 7
		replace bsu_j = "0" + substr(bsu_j,1,7) if strlen(bsu_j) == 7
		tempfile bsudist`i'
		save `bsudist`i''
	}


* Append in long format	
* =====================
	clear
	forvalues i=1(1)15{
		append using `bsudist`i''
	}

	collapse dist_km time_min , by(bsu_i bsu_j) // Take avg. of duplicate pairs

	
* Harmonize adm. changes in knr's and bsu's
* =========================================
	
	* i's
	gen bsu_cngfrom = bsu_i
	merge m:1 bsu_cngfrom using $dta\harmonize_bsu.dta, nogen keep(master matched)
	replace bsu_i = bsu_cngto if bsu_harmonize == 1
	replace bsu_i = "" if bsu_cngto == "DROP" 	// non-harmonizable
	drop bsu_cngfrom bsu_cngto bsu_harmonize

	* j's
	gen bsu_cngfrom = bsu_j
	merge m:1 bsu_cngfrom using $dta\harmonize_bsu.dta, nogen keep(master matched)
	replace bsu_j = bsu_cngto if bsu_harmonize == 1
	replace bsu_j = "" if bsu_cngto == "DROP" 	// non-harmonizable
	drop bsu_cngfrom bsu_cngto bsu_harmonize

	drop if bsu_i == "" | bsu_j == ""			// about 0.1 %

	sort bsu_i bsu_j
	
	save "$dta\ImportDistance.dta",replace
